package com.coconet.gas.rabbitMq.Consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coconet.gas.dao.OutTimeTaskMapper;
import com.coconet.gas.rabbitMq.config.RabbitMQConfig;
import com.coconet.gas.rabbitMq.entity.CheckEntity;
import com.coconet.gas.service.TaskService;
import com.coconet.gas.service.impl.OpenvasTool2;
import com.coconet.gas.vo.dw.OutTimeTask;
import com.gxa.entity.TargetEntity;
import com.gxa.entity.TaskEntity;
import com.gxa.entity.TaskInfoEntity;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RabbitListener(queues = RabbitMQConfig.RABBITMQ_DEMO_TOPIC)
public class RabbitDemoConsumer {

    @Resource
    private OpenvasTool2 openvasTool;
    @Resource
    private TaskService taskService;
    @Resource
    private OutTimeTaskMapper ottMapper;

    private static String portid = "4a4717fe-57d2-11e1-9a26-406186ea4fc5";

    public  volatile int taskNum = 0;
    //定义消费者   当taskNum小于15的时候就会触发  添加任务 如果不小于10  则执行等待
    @RabbitHandler
    public void process(Map checkEntitymap){

        CheckEntity checkEntity = new CheckEntity(checkEntitymap.get("msg").toString());
        //System.out.println(JSON.toJSONString(checkEntitymap));
        while(taskNum > 14){
            try{
                Thread.sleep(1000);
            }catch (Exception e){
            }
        }
        //发送何查信息
        for (int i = 0 ; i < checkEntity.getHosts().length;i++){
            //String targetid = "";
            //先验证是否存在此IP的查询目标
            String targetId = "";

            try {
                //获取targetId扫描任务的targetid

                List<TargetEntity> targetList = openvasTool.getTargetList();
                for (TargetEntity target : targetList) {
                    if (target.getHosts().equals(checkEntity.getHosts()[i])){
                        targetId = target.getUuid();
                        break;
                    }
                }

                /*String getTagetUrl = auditUrl + "/getTargetIdByIp/" + checkEntity.getHosts()[i];
                String getTargetRes = HttpUtil.sendGet(getTagetUrl, "", CheckTask.token);
                JSONObject resJson = (JSONObject) JSONObject.parse(getTargetRes);
                targetid = resJson.get("data").toString();*/
            } catch (Exception e) {
                //return Result.ok("creat error");
            }
            if("".equals(targetId)){
                //先添加扫描对象  在添加 扫描任务
                TargetEntity target = new TargetEntity();
                target.setHosts(checkEntity.getHosts()[i]);
                target.setName(checkEntity.getHosts()[i]);
                target.setPortId("730ef368-57e2-11e1-a90f-406186ea4fc5");

                try {
                    taskService.createTarget(target);
                } catch (Exception e) {
                    e.printStackTrace();
                }
               /* Map<String, Object> map = new HashMap<>();
                map.put("hosts", checkEntity.getHosts()[i]);
                map.put("name", checkEntity.getHosts()[i]);
                map.put("portId", portid);
                String url = auditUrl + "/createTarget";
                String res = HttpUtil.sendPost(url, JSON.toJSONString(map), CheckTask.token);
                if ("".equals(res)) {
                    return;
                }*/
            }
            try {
                //获取targetId扫描任务的targetid
                List<TargetEntity> targetList = openvasTool.getTargetList();
                for (TargetEntity target : targetList) {
                    if (target.getHosts().equals(checkEntity.getHosts()[i])){
                        targetId = target.getUuid();
                        break;
                    }
                }
               /* String getTagetUrl = auditUrl + "/getTargetIdByIp/" + checkEntity.getHosts()[i];
                String getTargetRes = HttpUtil.sendGet(getTagetUrl, "", CheckTask.token);
                JSONObject resJson = (JSONObject) JSONObject.parse(getTargetRes);
                targetid = resJson.get("data").toString();*/
            } catch (Exception e) {
                return ;
            }
            //继续执行添加扫描任务
            TaskEntity task = new TaskEntity();
            task.setType(Integer.valueOf(checkEntity.getType()));
            task.setCron(checkEntity.getCron());
            //task.setName(checkEntitymap.get("sendTime").toString()+":"+checkEntity.getName()+checkEntity.getHosts()[0]);
            task.setName(checkEntity.getName());
            task.setTargetId(targetId);
            try {
                taskService.createTask(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
            /*Map<String, Object> mapTask = new HashMap<>();
            mapTask.put("type", checkEntity.getType());
            mapTask.put("cron", checkEntity.getCron());
            mapTask.put("name", checkEntitymap.get("sendTime").toString()+":"+checkEntity.getName()+checkEntity.getHosts()[0]);
            mapTask.put("targetId", targetid);
            String urlTask = auditUrl + "/createTask";
            HttpUtil.sendPost(urlTask, JSON.toJSONString(mapTask), CheckTask.token);*/
        }
    }

    @Scheduled(cron="0/3 * *  * * ? ")
    public void getTaskNum(){

        /*if ("".equals(CheckTask.token)){
            return;
        }*/
        //发送请求 获取
        /*String url = auditUrl + "/getTasksNum";
        String res = HttpUtil.sendPost(url, "", CheckTask.token);
        HashMap hashMap = JSON.parseObject(res, HashMap.class);
        String num =hashMap.get("data").toString();*/
        int num = 0 ;
        try {
            num = openvasTool.getTasksNum();
        } catch (Exception e) {
            e.printStackTrace();
        }
        taskNum = Integer.valueOf(num);
    }

    @Scheduled(cron="0 0 0 * * ? ")
    //@Scheduled(cron="0 0/10 * * * ? ")
    public void dealOutTime(){
        try {
            List<TaskInfoEntity> tasksList = openvasTool.getTasksList();
            for (TaskInfoEntity task : tasksList) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
                //simpleDateFormat.format(task.getLastTime());
                Date dateCheck = simpleDateFormat.parse(task.getCheckTime());
                if ((new Date().getTime()-dateCheck.getTime())/(1000*3600*24)>=1 && task.getStatus().contains("等待中")){
                //if ( !task.getStatus().contains("已完成")){
                    OutTimeTask outTimeTask = new OutTimeTask();
                    outTimeTask.setTaskName(task.getName());
                    outTimeTask.setMsg("扫描超时!");
                    outTimeTask.setCheckTime(task.getCheckTime());
                    ottMapper.insert(outTimeTask);
                    openvasTool.deleteTask(task.getTaskId());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
